package com.flyco.modules.stm.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.stm.entity.*;
import com.flyco.modules.stm.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.entity.ImportParams;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 渠道表
 * @Author: flyco
 * @Date: 2023-06-21
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "渠道表")
@RestController
@RequestMapping("/f/stm/stmChannelInfo")
public class StmChannelInfoController extends BaseController<StmChannelInfo, IStmChannelInfoService> {
    @Autowired
    private IStmChannelInfoService stmChannelInfoService;
    @Autowired
    private IStmChannelProductService channelProductService;
    @Autowired
    private IStmChannelProductApplyService applyService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IStmChannelProductApplyItemService applyItemService;
    @Autowired
    private IStmChannelStoreRelationService stmChannelStoreRelationService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "渠道表-分页列表查询")
    @ApiOperation(value = "渠道表-分页列表查询", notes = "渠道表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StmChannelInfo stmChannelInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StmChannelInfo> queryWrapper = QueryGenerator.initQueryWrapper(stmChannelInfo, req.getParameterMap());
        Page<StmChannelInfo> page = new Page<StmChannelInfo>(pageNo, pageSize);
        IPage<StmChannelInfo> pageList = stmChannelInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     */
    @AutoLog(value = "渠道表-获取渠道")
    @ApiOperation(value = "渠道表-获取渠道", notes = "渠道表-获取渠道")
    @GetMapping(value = "/getChannelList")
    public Result<?> getChannelList() {
        LambdaQueryWrapper<StmChannelInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmChannelInfo::getStatus, 1);
        List<StmChannelInfo> list = stmChannelInfoService.list(queryWrapper);
        return Result.ok(list);
    }


    /**
     * 添加
     *
     * @param stmChannelInfo
     * @return
     */
    @AutoLog(value = "渠道表-添加")
    @ApiOperation(value = "渠道表-添加", notes = "渠道表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StmChannelInfo stmChannelInfo) {
        stmChannelInfo.setChannelId(RandomUtil.randomNumbers(5));
        stmChannelInfoService.save(stmChannelInfo);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param stmChannelInfo
     * @return
     */
    @AutoLog(value = "渠道表-编辑")
    @ApiOperation(value = "渠道表-编辑", notes = "渠道表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StmChannelInfo stmChannelInfo) {

        stmChannelInfoService.updateById(stmChannelInfo);

        //把关联的供应商渠道状态都更新
        stmChannelStoreRelationService.updateStatusByChannelId(stmChannelInfo.getStatus(), stmChannelInfo.getId());

        //更新

        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "渠道表-通过id删除")
    @ApiOperation(value = "渠道表-通过id删除", notes = "渠道表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        stmChannelInfoService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "渠道表-批量删除")
    @ApiOperation(value = "渠道表-批量删除", notes = "渠道表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stmChannelInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "渠道表-通过id查询")
    @ApiOperation(value = "渠道表-通过id查询", notes = "渠道表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StmChannelInfo stmChannelInfo = stmChannelInfoService.getById(id);
        return Result.ok(stmChannelInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param stmChannelInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmChannelInfo stmChannelInfo) {
        return super.exportXls(request, stmChannelInfo, StmChannelInfo.class, "渠道表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StmChannelInfo.class);
    }

    /**
     * 通过excel导入渠道产品价格数据
     */
    @RequestMapping(value = "/importChannelProductExcel", method = RequestMethod.POST)
    public Result<?> importChannelProductExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Integer channelId = Integer.valueOf(request.getParameter("channelId"));
        StmChannelInfo channelInfo = stmChannelInfoService.getById(channelId);
        if (channelInfo == null) {
            return Result.error("渠道Id值错误");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<StmChannelProductApplyItem> list = ExcelImportUtil.importExcel(file.getInputStream(), StmChannelProductApplyItem.class, params);
                List<StmChannelProductApplyItem> updateChannelProduct = new ArrayList<>();
                StmChannelProductApply apply = new StmChannelProductApply();
                for (StmChannelProductApplyItem channelProduct : list) {

                    if (StringUtils.isEmpty(channelProduct.getSkuCode())) {
                        continue;
                    }
                    PmsProduct productInfo = pmsProductService.getBySkuCode(channelProduct.getSkuCode());
                    if (productInfo == null) {
                        return Result.error("文件导入失败,物料编码:" + channelProduct.getSkuCode() + "没有找到对于的产品信息");
                    }
                    channelProduct.setProductSn(productInfo.getProductSn());
                    channelProduct.setProductName(productInfo.getName());
                    updateChannelProduct.add(channelProduct);
                }
                apply.setUserName(sysUser.getRealname());
                apply.setChannelName(channelInfo.getName());
                apply.setChannelId(channelId);
                apply.setUserId(sysUser.getId());
                applyService.save(apply);

                List<StmChannelProductApplyItem> newItemList =
                        updateChannelProduct
                                .stream()
                                .map(o -> {
                                            o.setApplyId(apply.getApplyId());
                                            o.setChannelId(channelId);
                                            return o;
                                        }
                                )
                                .collect(Collectors.toList());

                //给供应链发送审批邮件
                applyItemService.saveBatch(newItemList);

                applyItemService.sendMailForUpdatePrice(apply.getApplyId());
                return Result.ok("文件导入成功！EXCEL数据行数:" + updateChannelProduct.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 渠道申请价格审批通过
     */
    @AutoLog(value = "申请表-审核通过")
    @ApiOperation(value = "申请表-审核通过", notes = "申请表-审核通过")
    @GetMapping(value = "/approve")
    public Result<?> approve(Integer applyId, Integer status) {
        if (status != 2 && status != 3 && status != 4) {
            return Result.error("状态值错误！");
        }
        StmChannelProductApply applyInfo = new StmChannelProductApply();
        applyInfo.setStatus(status);
        applyInfo.setApplyId(applyId);
        applyService.updateById(applyInfo);

        //更新审批明细状态
        LambdaQueryWrapper<StmChannelProductApplyItem> applyItemWrapper = new LambdaQueryWrapper<>();
        applyItemWrapper.in(StmChannelProductApplyItem::getApplyId, applyId);
        StmChannelProductApplyItem applyItem = new StmChannelProductApplyItem();
        applyItem.setStatus(status);
        applyItem.setApplyId(applyId);
        applyItemService.update(applyItem, applyItemWrapper);

        if (status == 3) {
            //把审批通过的记录更新到表stm_channel_product中
            channelProductService.mergeIntoChannelProductByApplyId(applyId);
        }

        applyItemService.sendMailForUpdatePrice(applyId);

        return Result.ok("审批成功！");
    }

    /**
     * 获取渠道列表-包含是否配置订单起订信息
     */
    @AutoLog(value = "获取渠道列表-包含是否配置订单起订信息")
    @ApiOperation(value = "获取渠道列表-包含是否配置订单起订信息")
    @GetMapping(value = "/channelListAndOrderDistance")
    public Result<?> queryChannelListAndOrderDistance() {
        List<StmChannelInfo> storeInfoList = stmChannelInfoService.queryChannelListAndOrderDistance();
        return Result.ok(storeInfoList);
    }
}
